<template>
  <div class="doctor-information pad">
    <el-page-header class="page-header" @back="goBack" :content="title">
    </el-page-header>
    <div class="head info-head">
      <span>医生详情</span>
      <img v-if="status === '0'" src="../assets/images/auth_begin.png" />
      <img v-if="status === '1'" src="../assets/images/auth_waiting.png" />
      <img v-else-if="status === '2'" src="../assets/images/auth_pass.png" />
      <img v-else-if="status === '3'" src="../assets/images/auth_failed.png" />
    </div>
    <el-form :model="doctorInformation" ref="information" label-position="top" :rules="rules">
      <el-form-item label="医生编号" prop="clinicianNumber">
        <el-input v-model="doctorInformation.clinicianNumber" />
      </el-form-item>
      <el-form-item label="医生姓名" prop="clinicianName">
        <el-input v-model="doctorInformation.clinicianName" />
      </el-form-item>
      <el-form-item label="医生性别" prop="clinicianGender">
        <el-select v-model="doctorInformation.clinicianGender">
          <el-option label="男" :value="1"></el-option>
          <el-option label="女" :value="2"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="医生年龄" prop="clinicianAge">
        <el-input v-model="doctorInformation.clinicianAge" />
      </el-form-item>
      <el-form-item label="医生头像" prop="clinicianHeadPortrait">
        <el-upload
          class="avatar-uploader"
          action="https://jsonplaceholder.typicode.com/posts/"
          :show-file-list="false"
          :http-request="uploadAvatar"
          :data-type="1"
        >
          <img v-if="doctorInformation.clinicianHeadPortrait" :src="doctorInformation.clinicianHeadPortrait" class="avatar">
          <i v-else class="el-icon-upload upload-icon"></i>
          <div
            class="pre-box"
            @click.stop="previewImg('doctorInformation.clinicianHeadPortrait')"
            v-if="doctorInformation.clinicianHeadPortrait"
          >
            预览
          </div>
        </el-upload>
      </el-form-item>
      <el-form-item label="医生身份证正面照" prop="identityCardJsut">
        <el-upload
          class="avatar-uploader card"
          action="https://jsonplaceholder.typicode.com/posts/"
          :show-file-list="false"
          :http-request="uploadIDCardAbove"
        >
          <img v-if="doctorInformation.identityCardJsut" :src="doctorInformation.identityCardJsut" class="avatar">
          <i v-else class="el-icon-upload upload-icon"></i>
          <div
            class="pre-box"
            @click.stop="previewImg('doctorInformation.identityCardJsut')"
            v-if="doctorInformation.identityCardJsut"
          >
            预览
          </div>
        </el-upload>
      </el-form-item>
      <el-form-item label="医生身份证反面照" prop="identityCardBack">
        <el-upload
          class="avatar-uploader card"
          action="https://jsonplaceholder.typicode.com/posts/"
          :show-file-list="false"
          :http-request="uploadIDCardBack"
        >
          <img v-if="doctorInformation.identityCardBack" :src="doctorInformation.identityCardBack" class="avatar">
          <i v-else class="el-icon-upload upload-icon"></i>
          <div
            class="pre-box"
            @click.stop="previewImg('doctorInformation.identityCardBack')"
            v-if="doctorInformation.identityCardBack"
          >
            预览
          </div>
        </el-upload>
      </el-form-item>
      <el-form-item label="医生执业证书" prop="clinicianLicense">
        <el-upload
          class="avatar-uploader card"
          action="https://jsonplaceholder.typicode.com/posts/"
          :show-file-list="false"
          :http-request="uploadWorkLicense"
        >
          <img v-if="doctorInformation.clinicianLicense" :src="doctorInformation.clinicianLicense" class="avatar">
          <i v-else class="el-icon-upload upload-icon"></i>
          <div
            class="pre-box"
            @click.stop="previewImg('doctorInformation.clinicianLicense')"
            v-if="doctorInformation.clinicianLicense"
          >
            预览
          </div>
        </el-upload>
      </el-form-item>
      <el-form-item label="医生从业资格证书" prop="clinicianQualification">
        <el-upload
          class="avatar-uploader card"
          action="https://jsonplaceholder.typicode.com/posts/"
          :show-file-list="false"
          :http-request="uploadDoctorLicense"
        >
          <img v-if="doctorInformation.clinicianQualification" :src="doctorInformation.clinicianQualification" class="avatar">
          <i v-else class="el-icon-upload upload-icon"></i>
          <div
            class="pre-box"
            @click.stop="previewImg('doctorInformation.clinicianQualification')"
            v-if="doctorInformation.clinicianQualification"
          >
            预览
          </div>
        </el-upload>
      </el-form-item>
      <el-form-item label="医生所属医院" prop="hospitalId">
        <el-select v-model="doctorInformation.hospitalId">
          <el-option v-for="(item, index) in allHospital" :key="index" :value="item.hospitalId" :label="item.hospitalName"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="医生擅长领域" prop="doctorLabelId">
        <el-select v-model="doctorInformation.doctorLabelId" multiple>
          <el-option v-for="(item, i) in allDoctorLabel" :key="i" :value="item.doctorLabelId" :label="item.doctorLabelName"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="医生所属科室" prop="departmentId">
        <!-- <el-input v-model="doctorInformation.clinicianDepartment" /> -->
        <el-select v-model="doctorInformation.departmentId">
          <el-option v-for="(item, index) in allDepartment" :key="index" :value="item.departmentId" :label="item.department"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="职称" prop="doctorTitleId">
        <el-select v-model="doctorInformation.doctorTitleId">
          <el-option v-for="(item, index) in allCareer" :key="index" :value="item.doctorTitleId" :label="item.doctorTitle"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="医生简述(选填)" prop="clinicianDesc">
        <el-input rows="5" type="textarea" v-model="doctorInformation.clinicianDesc" />
      </el-form-item>
    </el-form>
    <el-button type="primary" @click="saveInformation('information')" :loading="isDoing">保 存</el-button>
    <el-button type="primary" v-if="status === '1'" @click="passCheck">通过审核</el-button>
    <el-button type="danger" v-if="status === '1'" @click="refuseCheck">驳回审核</el-button>
    <div class="mask-wrap" v-if="showMask" @click="hideMask">
      <img :src="previewUrl" @click.stop="stopBubble" />
    </div>
  </div>
</template>
<script>
import {
  getAllHospital,
  getAllDoctorLabel,
  finishDoctorInformation,
  getDoctorInformation,
  setDoctorInformationStatus,
  getAllDepartment,
  getAllCareer,
  sendSubscription
} from '../api/hospitalAPI';
import { uploadImage } from '../api';
import {
  fileToBase64, formatDate
} from '../util/index';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';

export default {
  name: 'DoctorInformation',
  props: ['id', 'status'],
  data () {
    return {
      isDoing: false,
      doctorInformation: { // 医生基本信息
        clinicianNumber: '',
        psychologicalClinicianId: '',
        clinicianName: '',
        clinicianGender: '',
        clinicianAge: '',
        clinicianHeadPortrait: '',
        identityCardJsut: '',
        identityCardBack: '',
        clinicianLicense: '',
        clinicianQualification: '',
        hospitalId: '',
        doctorLabelId: '',
        doctorLabelName: '',
        clinicianDepartment: '',
        clinicianDesc: '',
        doctorTitleId: '',
        departmentId: ''
      },
      allHospital: [],
      allDoctorLabel: [],
      allDepartment: [],
      allCareer: [],
      rules: {
        clinicianNumber: [
          { required: true, message: '医生编号不能为空', trigger: 'blur' }
        ],
        clinicianName: [
          { required: true, message: '医生姓名不能为空', trigger: 'blur' }
        ],
        clinicianGender: [
          { required: true, message: '医生性别不能为空', trigger: 'blur' }
        ],
        clinicianAge: [
          { required: true, message: '医生年龄不能为空', trigger: 'blur' }
        ],
        clinicianHeadPortrait: [
          { required: true, message: '医生头像不能为空', trigger: 'blur' }
        ],
        identityCardJsut: [
          { required: true, message: '请上传医生身份证正面照', trigger: 'blur' }
        ],
        identityCardBack: [
          { required: true, message: '请上传医生身份证反面照', trigger: 'blur' }
        ],
        clinicianLicense: [
          { required: true, message: '请上传医生执业证', trigger: 'blur' }
        ],
        clinicianQualification: [
          { required: true, message: '请上传医生资格证书', trigger: 'blur' }
        ],
        hospitalId: [
          { required: true, message: '请选择所属医院', trigger: 'blur' }
        ],
        doctorLabelId: [
          { required: true, message: '请选择擅长领域', trigger: 'blur' }
        ],
        departmentId: [
          { required: true, message: '请填写所属科室', trigger: 'blur' }
        ],
        clinicianDesc: [
          { required: true, message: '请填写医生描述', trigger: 'blur' }
        ],
        doctorTitleId: [
          { required: true, message: '医生职称不能为空', trigger: 'blur' }
        ]
      },
      previewUrl: '',
      showMask: false,
      openId: null,
      createDate: null
    }
  },
  methods: {
    stopBubble () {},
    goBack () {
      history.back()
    },
    hideMask () { // 隐藏预览框
      this.previewUrl = '';
      this.showMask = false
    },
    fetchAllHospital () { // 获取所有医院
      getAllHospital()
      .then(res => {
        if (res.data.code === 1) {
          this.allHospital = res.data.data || [];
          console.log(this.allHospital)
        } else {
          this.$message.error(res.data.msg || '服务异常!')
        }
      })
      .catch(e => {
        this.$message.error('服务异常!')
      })
    },
    fetchAllDoctorLabel () { // 获取所有医生标签
      getAllDoctorLabel()
      .then(res => {
        if (res.data.code === 1) {
          this.allDoctorLabel = res.data.data || [];
        } else {
          this.$message.error(res.data.msg || '服务异常!')
        }
      })
      .catch(e => {
        this.$message.error('服务异常!')
      })
    },
    saveInformation (name) { // 保存基本信息
      this.$refs[name].validate(valid => {
        if (valid) {
          this.isDoing = true;
          let str = '';
          for (let i = 0; i < this.doctorInformation.doctorLabelId.length; i ++) {
            let name = this.allDoctorLabel.filter(item => item.doctorLabelId === this.doctorInformation.doctorLabelId[i])[0].doctorLabelName;
            str += `${name},`
          };
          finishDoctorInformation({
            clinicianNumber: this.doctorInformation.clinicianNumber,
            psychologicalClinicianId: Number(this.id),
            clinicianName: this.doctorInformation.clinicianName,
            clinicianGender: this.doctorInformation.clinicianGender,
            clinicianAge: this.doctorInformation.clinicianAge,
            clinicianHeadPortrait: this.doctorInformation.clinicianHeadPortrait,
            identityCardJsut: this.doctorInformation.identityCardJsut,
            identityCardBack: this.doctorInformation.identityCardBack,
            clinicianLicense: this.doctorInformation.clinicianLicense,
            clinicianQualification: this.doctorInformation.clinicianQualification,
            hospitalId: this.doctorInformation.hospitalId,
            doctorLabelId: this.doctorInformation.doctorLabelId.join(','),
            doctorLabelName: str.slice(0, str.length - 1),
            // clinicianDepartment: this.doctorInformation.clinicianDepartment,
            departmentId: this.doctorInformation.departmentId,
            doctorTitleId: this.doctorInformation.doctorTitleId,

            clinicianDesc: this.doctorInformation.clinicianDesc
          })
          .then(res => {
            if (res.data.code === 1) {
              this.$message({
                type: 'success',
                message: '信息更改成功',
                onClose: () => {
                  this.$router.back()
                }
              })
            } else {
              this.$message.error(res.data.msg || '服务异常!')
            };
            this.isDoing = false
          })
          .catch(e => {
            this.isDoing = false;
            this.$message.error('服务异常!')
          })
        } else {
          return false
        }
      })
    },
    handleUploadDoctorImg (file, type) { // 上传医生个人信息相关图片
      NProgress.start();
      fileToBase64(file, base => {
        uploadImage(base)
        .then(res => {
          if (res.data.code === 1) {
            let { path } = res.data.data;
            let newPath = path.replace(':', 's:');
            if (type === 1) { // 上传头像
              this.doctorInformation.clinicianHeadPortrait = newPath
            } else if (type === 2) { // 上传身份证正面
              this.doctorInformation.identityCardJsut = newPath
            } else if (type === 3) { // 上传身份证反面
              this.doctorInformation.identityCardBack = newPath
            } else if (type === 4) { // 上传执业证
              this.doctorInformation.clinicianLicense = newPath
            } else if (type === 5) { // 上传医生资格证书
              this.doctorInformation.clinicianQualification = newPath
            }
          } else {
            this.$message.error(res.data.msg || '服务异常!')
          };
          NProgress.done()
        })
        .catch(e => {
          NProgress.done();
          this.$message.error('服务异常!')
        })
      })
    },
    uploadAvatar ({ file }) { // 上传头像
      this.handleUploadDoctorImg(file, 1)
    },
    uploadIDCardAbove({ file }) { // 上传身份证正面
      this.handleUploadDoctorImg(file, 2)
    },
    uploadIDCardBack({ file }) { // 上传身份证反面
      this.handleUploadDoctorImg(file, 3)
    },
    uploadWorkLicense({ file }) { // 上传执业证
      this.handleUploadDoctorImg(file, 4)
    },
    uploadDoctorLicense({ file }) { // 上传医生资格证书
      this.handleUploadDoctorImg(file, 5)
    },
    fetchInformationByDoctorId (id) { // 根据医生id查询详细信息
      NProgress.start();
      getDoctorInformation(id)
      .then(res => {
        if (res.data.code === 1) {
          let info = res.data.data;
          NProgress.done();
          if (!info) return;
          this.doctorInformation.clinicianNumber = info.clinicianNumber;
          this.doctorInformation.clinicianName = info.clinicianName;
          this.doctorInformation.clinicianGender = Number(info.clinicianGender);
          this.doctorInformation.clinicianAge = info.clinicianAge;
          this.doctorInformation.clinicianHeadPortrait = info.clinicianHeadPortrait;
          this.doctorInformation.identityCardJsut = info.identityCardJsut;
          this.doctorInformation.identityCardBack = info.identityCardBack;
          this.doctorInformation.clinicianLicense = info.clinicianLicense;
          this.doctorInformation.clinicianQualification = info.clinicianQualification;
          this.doctorInformation.hospitalId = Number(info.hospitalId);
          this.openId = info.clinicianOpenId;
          this.createDate = formatDate(info.createDate, 'zh:');
          let list = info.doctorLabelId && info.doctorLabelId.split(',').map(Number);
          let tempList = [];
          for (let i = 0; i < list.length; i ++) { // 过滤掉已被删除的标签
            for (let j = 0; j < this.allDoctorLabel.length; j ++) {
              if (this.allDoctorLabel[j].doctorLabelId == list[i]) {
                tempList.push(this.allDoctorLabel[j].doctorLabelId)
              }
            }
          };
          this.doctorInformation.doctorLabelId = tempList;
          // this.doctorInformation.clinicianDepartment = info.clinicianDepartment;
          this.doctorInformation.departmentId = Number(info.departmentId);
          this.doctorInformation.doctorTitleId = Number(info.doctorTitleId);
          this.doctorInformation.clinicianDesc = info.clinicianDesc
        } else {
          NProgress.done();
          this.$message.error('服务异常!')
        }
      })
      .catch(e => {
        NProgress.done();
        this.$message.error('服务异常!')
      })
    },
    passCheck () { // 通过请求
      this.handleSetInformationStatus(2)
    },
    refuseCheck () { // 驳回请求
      this.$confirm('确定驳回此医生的身份信息审核?, 驳回后此医生无法正常使用小程序', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(res => {
        this.handleSetInformationStatus(3)
      })
      .catch(e => {
        this.$message({
          type: 'info',
          message: '取消操作'
        })
      })
    },
    handleSetInformationStatus (status) { // 设置医生信息状态 0: 初始状态 1: 审核状态 2: 成功状态 3: 失败状态
      const _this = this;
      setDoctorInformationStatus(Number(this.id), status)
      .then(res => {
        if (res.data.code === 1) {
          let resText = '';
          if (status === 2) {
            resText = '审核通过'
          } else if (status === 3) {
            resText = '审核未通过'
          };
          let obj = {
            phrase1: {
              value: resText
            },
            thing2: {
              value: '知心意管理医生认证申请'
            },
            date3: {
              value: formatDate(Date.now(), 'zh:')
            },
            date4: {
              value: _this.createDate
            },
            thing7: {
              value: '如有疑问请联系管理员'
            }
          };
          sendSubscription({
            touser: _this.openId,
            templateId: 'ltaS9T_2smSKRzeOPE5Y2belmoxKJofjRvLawsBw3JM',
            page: 'pages/home/home',
            data: JSON.stringify(obj),
            type: 2
          })
          .then(res => {

          })
          .catch(e => {

          });
          this.$message({
            type: 'success',
            message: '操作成功!',
            onClose: () => {
              this.$router.back()
            }
          })
        } else {
          this.$message.error(res.data.msg || '服务异常!')
        }
      })
      .catch(e => {
        this.$message.error('服务异常!')
      })
    },
    fetchAllDepartment () { // 获取所有科室
      getAllDepartment()
      .then(res => {
        if (res.data.code === 1) {
          let list = res.data.data || [];
          this.allDepartment = list
        } else {
          this.$message.error(res.data.msg || '服务异常!')
        }
      })
      .catch(e => {
        this.$message.error('服务异常!')
      })
    },
    fetchAllCareer () { // 获取所有职称
      getAllCareer()
      .then(res => {
        if (res.data.code === 1) {
          let list = res.data.data || [];
          this.allCareer = list
        } else {
          this.$message.error(res.data.msg || '服务异常!')
        }
      })
      .catch(e => {
        this.$message.error('服务异常!')
      })
    },
    previewImg (url) { // 预览图片
      let urlArr = url.split('.');
      this.showMask =  true;
      this.previewUrl = this[urlArr[0]][urlArr[1]]
    }
  },
  created () {
    let path = this.$route.meta.path;
    this.title = path[path.length - 1];
    this.fetchAllHospital();
    this.fetchAllDoctorLabel();
    this.fetchInformationByDoctorId(Number(this.id));
    this.fetchAllDepartment();
    this.fetchAllCareer()
  }
}
</script>
<style lang="scss">
  .mask-wrap {
    position: fixed;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    background-color: rgba(0, 0, 0, .5);
    z-index: 999;
    overflow: auto;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .mask-wrap img {
    max-width: 90%;
  }
  .doctor-information {
    .info-head {
      position: relative;
      img {
        position: absolute;
        left: 70px;
        top: -40px;
        width: 128px;
        height: 128px;
      }
    }
  }
  .avatar-uploader .el-upload {
    position: relative;
    display: flex;
    align-items: center;
    justify-content: center;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    width: 200px;
    min-height: 200px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    box-sizing: border-box;
  }
  .pre-box {
    position: absolute;
    top: 0;
    right: 0;
    width: 60px;
    height: 60px;
    background-color: rgba(0, 0, 0, .7);
    border-bottom-left-radius: 30px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 20px;
    font-weight: bold;
    color: #ffffff;
  }
  .avatar-uploader .avatar {
    display: block;
    width: 200px;
    height: 200px;
  }
  .avatar-uploader.card .avatar {
    width: 300px;
    height: auto!important;
  }
  .card .el-upload {
    width: 300px;
    // height: 200px;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .upload-icon {
    display: block;
    font-size: 60px;
  }
  .pre-box img {
    width: 30px;
    height: 30px;
  }
</style>
